package com.mangguo.tingjian.config.db;


import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import lombok.val;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.web.servlet.resource.PathResourceResolver;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@MapperScan(basePackages = {
        "com.mangguo.tingjian.account.mapper",
        "com.mangguo.tingjian.activity.mapper",
        "com.mangguo.tingjian.content.mapper",
        "com.mangguo.tingjian.statistics.mapper",
        "com.mangguo.tingjian.user.mapper"
}, sqlSessionFactoryRef = "visualSqlSessionFactory")
public class DataSourceVisualConfig {

    @Bean(name = "visualDataSource")
    @Primary
    @ConfigurationProperties("spring.datasource.visual")
    public DataSource visualDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "visualSqlSessionFactory")
    @Primary
    public SqlSessionFactory visualSqlSessionFactory(@Qualifier("visualDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "visualDataSourceTransactionManager")
    @Primary
    public DataSourceTransactionManager visualDataSourceTransactionManager(@Qualifier("visualDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "visualSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate visualSqlSessionTemplate(@Qualifier("visualSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
